    
import lrz from 'lrz';
import { dataURLtoFile } from "@/utils/64batatoFile";
import {
  upload,photoMake
} from "@/api/apply.js";

var data = {
    exact:'environment',
    mediaList:[],
    time:null,
    resolutionRatio:{},
    width:'',
    height:'',
    imgBackUrl:'',
}
export default {
    // created(that){
    //     this.data.that = that
    // },
    methods: {
        async onclick(){
            let widowWidth = document.documentElement.clientWidth || document.body.clientWidth
            data.width = widowWidth * 0.8
            data.height = widowWidth*1.28 * 0.8
            
            if(this.type=='photo'){
              data.width = widowWidth * 0.8
              data.height = widowWidth*1.28 * 0.8
              data.resolutionRatio={
                width: data.height,
                height: data.width,
              }
            }else
            if(['id_card_photo','id_card_emblem'].includes(this.type)){
              data.width = widowWidth
              data.height = widowWidth*0.63
              data.resolutionRatio={
                  // width:widowWidth * 0.8,
                  // height:widowWidth*1.28 * 0.8,
                  width: data.height,
                  height: data.width,
              }
            }else{
              data.width = widowWidth
              data.height = widowWidth*0.75
              data.resolutionRatio={
                  width: data.height,
                  height: data.width,
              }
            }
            this.cropParams.size = {
              width: data.width*2,
              height: data.height*2,
            }
            if(!this.$refs.camera){
              this.$refs.upload.click()
              return
            }
            this.$refs.camera.width = data.width
            this.$refs.camera.height =data.height
            if(this.type=='photo'){
              data.exact = 'user'
            }else{
              data.exact = 'environment'
            }
            await navigator.mediaDevices.enumerateDevices().then((devices) => {
              data.mediaList = devices
            });
          // await this.getUserMedia().then(async res=>{
          //   if(res){
          //     this.showCamera = true
          //     if(this.type=='photo'){
          //       data.exact = 'user'
          //     }else{
          //       data.exact = 'environment'
          //     }
              
          //     this.useCamera()
          //   }else{
          //     this.$refs.upload.click()
          //   }
          // })
          
          this.useCamera()
        },
		// 获取到图片
       async onchange(event){
          this.showCamera=false
          const file = event.target.files[0]
          
          if(this.corp){
            await lrz(file,{quality:1}).then(res=>{
              this.isShowImgCard=true
              this.cropParams.src = res.base64
              this.cropParams.label =  file.name
              this.$nextTick(()=>{
                this.$refs.SimpleCrop?._instance.$resetBtn.click()
              })
            })
          }else{
            let files = null
            if (this.zip) {  //是否开启图片压缩
              await lrz(file,{quality:0.8}).then(resA=>{
                  files = new File([resA.file], file.name, {type:'image/png'})
              })
            }else{
                files = file
            }
            
            upload({img:files}).then(res=>{
              this.$emit('change',{files,res,field_id:this.type,ocr:true})
            })
          }
          
        },
        //剪辑图片
        async crop(data) {
          //传入后台的file对象
          // this.isShowImgCard=false
          //   this.showProBack=true
          this.openImgBack(data.toDataURL())
        },
        //删除图片
        remove(){
          this.imgurl = ''
          this.$emit('change',{files:null,res:{code:9000},field_id:this.type,ocr:false})
        },
        //使用摄像头
        useCamera(){
            let deviceId=''
            data.mediaList.map((item)=>{
              if(item.deviceId&&item.deviceId!='default'){
                deviceId=item.deviceId
              }
            })
            // let list = data.mediaList.filter(item=>item.deviceId&&item.deviceId!='default'&&item.kind=='videoinput')
            // if(list.length!=0){
            //   if(list.length>1){
            //     if(data.exact=='user'){
            //       deviceId=list[0].deviceId
            //     }else{
            //       deviceId=list[1].deviceId
            //     }
            //   }else{
            //     deviceId=list[0].deviceId
            //   }
            // }
            // alert(deviceId,'88888')
            // console.log(data.mediaList,'521233');
            // console.log(deviceId,'88888');
            this.$refs.camera.width = data.width
            this.$refs.camera.height =data.height
            if(data.exact=='user'){
              this.$refs.camera.style.transform='rotateY(-180deg)'
            }else{
              this.$refs.camera.style.transform = ''
            }
            let obj = {}
            if(this.type=='photo'){
              obj = {
                facingMode: data.exact,
                minwidth:data.resolutionRatio.width*6,
                minheight:data.resolutionRatio.height*6,
              }
              if(deviceId){
                obj = {
                  facingMode: data.exact,
                  minwidth:data.resolutionRatio.width*6,
                  minheight:data.resolutionRatio.height*6,
                  deviceId:deviceId
                }
              }
            }else{
              obj = {
                width:data.resolutionRatio.width,
                height:data.resolutionRatio.height,
                facingMode:data.exact,
              }
              if(deviceId){
                obj = {
                  width:data.resolutionRatio.width,
                  height:data.resolutionRatio.height,
                  facingMode:data.exact,
                  deviceId:deviceId
                }
              }
            }
            // if(deviceId){
            //   obj = {
            //     width:data.resolutionRatio.width,
            //     height:data.resolutionRatio.height,
            //     facingMode:data.exact,
            //     deviceId:deviceId,
            //   } 
            // }else{
            //   obj = {
            //     width:data.resolutionRatio.width,
            //     height:data.resolutionRatio.height,
            //     facingMode:data.exact,
            //   }
            // }
            // console.log(obj,'858484');
            try{
              navigator.mediaDevices.getUserMedia({ video: obj,audio: false}).then(res=>{
                this.showCamera = true
                navigator.mediaDevices.enumerateDevices().then((devices) => {
                  data.mediaList = devices
                });
                this.$refs.camera.srcObject=res
                this.$refs.camera.setAttribute('playsinline', true)
                this.$refs.camera.setAttribute('webkit-playsinline', true)
                this.$refs.camera.play()
                this.$forceUpdate();
              }).catch(()=>{
                this.$refs.upload.click()
              })
            }catch{
              this.$refs.upload.click()
            }
            
        },
        //检测摄像头是否可用
        async getUserMedia(constraints, success, error) {
            try {
              return new Promise(async (resolve) => {
                //最新的标准API
                await navigator.mediaDevices
                  .getUserMedia({ video: { width: data.resolutionRatio.width, height: data.resolutionRatio.height },audio: false })
                  .then(() => {
                    resolve(true);
                  })
                  .catch((res) => {
                    resolve(false);
                  });
              });
            } catch {
              return new Promise((resolve) => {
                resolve(false);
              });
            }
        },
        //关闭摄像头
        closeCamera() {
            let video = this.$refs.camera
            if (video&&video.srcObject) {
                video.srcObject.getTracks().forEach((track) => {
                    track.stop()
                })
            }
        },
        //切换摄像头
        changeCamera(){
            if(this.type!='photo'){
              data.exact = 'environment'
              return 
            }
            if(data.exact=='user'){
                data.exact = 'environment'
            }else{
                data.exact='user'
            }
            this.closeCamera()
            this.useCamera()
        },
        //拍照
        takePhoto(){
          let canvas = document.createElement('canvas')
          canvas.width = this.$refs.camera.width * 4
          canvas.height = this.$refs.camera.height * 4
          canvas.style = `display:none;height:${this.$refs.camera.height};width:${this.$refs.camera.width};`
          let ctx = canvas.getContext('2d')
          ctx.scale(4,4)
          if(data.exact=='user'){
            ctx.translate( this.$refs.camera.width, 0);
            ctx.scale(-1, 1); //左右镜像翻转
          }else{
            ctx.translate( 0, 0);
            ctx.scale(1, 1); //左右镜像翻转
          }
          ctx.drawImage(this.$refs.camera,0,0,this.$refs.camera.width,this.$refs.camera.height)
          const img = canvas.toDataURL('image/png')
          // event.target.files[0]
          this.onchange({
            target:{
              files:[
                dataURLtoFile(img,this.type+'.png')
              ]
            }
          })
        },
        //关闭裁剪
        closeCrop(){
          this.openImgBack(this.cropParams.src)
          // this.removeDomCrop()
        },
        //移除裁剪dom
        removeDomCrop(){
          window.ontouchmove = null
          window.ontouchstart = null
          window.removeEventListener('touchstart',()=>{})
          window.removeEventListener('ontouchmove',()=>{})
          if(document.getElementsByClassName('crop-whole-cover')&&document.getElementsByClassName('crop-whole-cover')[0]){
            document.body.removeChild(document.getElementsByClassName('crop-whole-cover')[0])
          }
        },
        //打开修改背景图片模块
        async openImgBack(src){
          this.backPhoto = src
          data.imgBackUrl = src
          let files = null
          let setting = JSON.parse(this.init.setting)
          if(this.type!='photo'){
            // let files = dataURLtoFile(this.cropParams.src)
            if (this.zip) {  //是否开启图片压缩
              await lrz(src,{quality:0.8}).then(res=>{
                  files = new File([res.file], this.cropParams.label, {type: res.file.type})
              })
            }else{
                files = dataURLtoFile(src)
            }
            this.CropLoading=true
            upload({img:files}).then(res=>{
              this.CropLoading=false
              if(res.code==200){
                //封面
                lrz(src,{quality:0.2}).then(res=>{
                  this.imgurl = res.base64
                })
              }
              this.cropParams.src=''
              this.isShowImgCard=false
              this.$emit('change',{files,res,field_id:this.type,ocr:false})
            })
            return
          }
          if(setting.backgroundPhoto &&
          (setting.backgroundPhoto == '是' ||
          setting.backgroundPhoto == '高级')){
            this.isShowImgCard=false
            this.showProBack=true
          }else{
            if (this.zip) {  //是否开启图片压缩
              await lrz(src,{quality:0.8}).then(res=>{
                  files = new File([res.file], this.cropParams.label, {type: res.file.type})
              })
            }else{
                files = dataURLtoFile(src)
            }
            this.CropLoading=true
          // let files = dataURLtoFile(this.cropParams.src)
            upload({img:files}).then(res=>{
              this.CropLoading=false
              if(res.code==200){
                //封面
                lrz(this.cropParams.src,{quality:0.2}).then(res=>{
                  this.imgurl = res.base64
                })
              }
              this.cropParams.src=''
              this.isShowImgCard=false
              this.$emit('change',{files,res,field_id:this.type,ocr:false})
            })
          }
        },
        //点击对应颜色修改背景色
        checkBackGround(col){
          let color = "#ffffff";
          if (col == 0) {
            color = "#ffffff";
          }
          if (col == 1) {
            color = "#6495ED";
          }
          if(col==3){
            color = "#fff000"
          }
          this.showProBackLoading = true;
          lrz(data.imgBackUrl,{quality:0.8}).then(async resa=>{
              await photoMake({
                url: resa.base64,
                bk: color,
                spec: 1, //一寸 1 二寸 4
              }).then((res) => {
                this.showProBackLoading = false;
                if (res.code == 200) {
                  this.backPhoto = res.data.result;
                
                } else {
                  this.$hint.error("仅支持人像底色修改!");
                }
              });
          })
        },
        //关闭背景图片更改
        async closeImgBack(){
          let src = data.imgBackUrl
          let files = null
          if (this.zip) {  //是否开启图片压缩
            await lrz(src,{quality:0.8}).then(res=>{
                files = new File([res.file], this.cropParams.label, {type: res.file.type})
            })
          }else{
              files = dataURLtoFile(src)
          }
          upload({img:files}).then(res=>{
            if(res.code==200){
              //封面
              lrz(this.cropParams.src,{quality:0.2}).then(res=>{
                this.imgurl = res.base64
              })
            }
            this.showProBack=false
            this.$emit('change',{files,res,field_id:this.type,ocr:false})
          })
        },
        //提交修改背景图片
       async commitImgBack(){
          if(!this.backPhoto){
            this.closeImgBack()
            return
          }
          let files = null
          if (this.zip) {  //是否开启图片压缩
            await lrz(this.backPhoto,{quality:0.8}).then(res=>{
                files = new File([res.file], this.cropParams.label, {type: res.file.type})
            })
          }else{
              let url = this.backPhoto;
              if (process.env.NODE_ENV === "development") {
                url =
                  "/photoMake" +
                  res.data.result.split("https://oapi.aisegment.com")[1];
              } else {
                url = res.data.result;
              }
              await fetch(url, {
                mode: "no-cors",
              })
                .then((res) => {
                  return res.blob();
                })
                .then((blob) => {
                  files = new File([blob], "photo.png", {
                    type: "image/jpeg",
                  });
                })
                .catch((err) => {});
              // files = dataURLtoFile(this.backPhoto)
          }
          upload({img:files}).then(res=>{
            if(res.code==200){
              //封面
              lrz(this.backPhoto,{quality:0.2}).then(res=>{
                this.imgurl = res.base64
              })
            }
            this.showProBack=false
            this.$emit('change',{files,res,field_id:this.type,ocr:false})
          })
        }
    }
}